using Dapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.PurchasingManagement.PurchaseOrders;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.PurchaseOrders;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace RBAC.Write.Api.Application.Handler.ERP.PurchasingManagement.PurchaseOrders
{
    /// <summary>
    /// 批量逻辑删除采购订单
    /// </summary>
    public class BatchDeletePurchaseOrdersCommandHandler : IRequestHandler<BatchDeletePurchaseOrdersCommand, APIResult<int>>
    {
        private readonly IBaseRepository<PurchaseOrderInfo> _repo;
        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<BatchDeletePurchaseOrdersCommandHandler> _logger;

        public BatchDeletePurchaseOrdersCommandHandler(
            IBaseRepository<PurchaseOrderInfo> repo,
            IDbConnectionFactory connectionFactory,
            ILogger<BatchDeletePurchaseOrdersCommandHandler> logger)
        {
            _repo = repo;
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BatchDeletePurchaseOrdersCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<int>();
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "未指定要删除的ID", Data = 0 });
                }

                // 可选：不允许删除已审核单据
                // var cntApproved = _repo.QueryCount("docStatus = @st AND Id IN @Ids AND IsDeleted = 0", new { st = "已审核", request.Ids });
                // if (cntApproved > 0) {
                //     return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "存在已审核单据，禁止删除", Data = 0 });
                // }

                using var conn = _connectionFactory.CreateConnectionWithRetry();
                using var tran = conn.BeginTransaction();

                // 主表逻辑删除
                var sqlMain = "UPDATE PurchaseOrderInfo SET IsDeleted = 1 WHERE Id IN @Ids AND IsDeleted = 0";
                var affectedMain = conn.Execute(sqlMain, new { request.Ids }, tran);

                // 明细表逻辑删除
                var sqlDetail = "UPDATE PurchasingMaterialInfo SET IsDel = 1 WHERE PurchaseOrderId IN @Ids AND IsDel = 0";
                var affectedDetail = conn.Execute(sqlDetail, new { request.Ids }, tran);

                tran.Commit();

                res.Code = APIEnums.Success;
                res.Msg = "批量删除成功";
                res.Data = affectedMain; // 返回主表受影响行数
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除采购订单失败: {Message}", ex.Message);
                return Task.FromResult(new APIResult<int> { Code = APIEnums.Error, Msg = "批量删除失败", Data = 0 });
            }

            return Task.FromResult(res);
        }
    }
}
